﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;

using TableTop.DataManagement.Addon;

namespace TableTop.Presentation.Controls
{
    [TemplatePart(Name = GridIconPart, Type = typeof(Grid))]
    public class AddonDockElement
        : Control
    {
        private Grid grdIcon = null;

        private const String GridIconPart = "grdIcon";

        
        public static DependencyProperty AddonInformationProperty = DependencyProperty.Register("AddonInformation",
                                                                                                typeof(AddonInfo),
                                                                                                typeof(AddonDockElement),
                                                                                                new PropertyMetadata(null));        
        public AddonInfo AddonInformation
        {
            get
            {
                return (AddonInfo)this.GetValue(AddonInformationProperty);
            }
            set
            {
                this.SetValue(AddonInformationProperty, value);
                this.SetElementsBindings();
            }
        }

        public AddonDockElement()
        {
            this.DefaultStyleKey = typeof(AddonDockElement);            
        }       

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            this.LocateComponents();
            this.SetElementsBindings();
        }

        private void LocateComponents()
        {
            this.grdIcon = this.Template.FindName(GridIconPart, this) as Grid;
        }

        private void SetElementsBindings()
        {
            ImageBrush iBrush = null;
            BitmapImage biImage = null;
            StringBuilder sbAddonTooltip = null;

            if (this.grdIcon != null)
            {
                if (this.AddonInformation != null)
                {
                    if (this.AddonInformation.AddonIcon != String.Empty)
                    {
                        biImage = new BitmapImage(new Uri(this.AddonInformation.AddonIcon));
                        iBrush = new ImageBrush(biImage);
                        this.grdIcon.Background = iBrush;
                    }

                    sbAddonTooltip = new StringBuilder();
                    sbAddonTooltip.Append(this.AddonInformation.Name);
                    sbAddonTooltip.Append(Environment.NewLine);
                    sbAddonTooltip.Append(this.AddonInformation.Description);
                    this.grdIcon.ToolTip = sbAddonTooltip.ToString();
                }
            }
        }
    }
}
